package com.lzxuni.modules.Seed.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzxuni.common.utils.FileUtil;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.utils.UuidUtil;
import com.lzxuni.common.utils.date.DateUtil;
import com.lzxuni.modules.Seed.entity.SeedInfo;
import com.lzxuni.modules.Seed.service.SeedInfoService;
import com.lzxuni.modules.basics.entity.BasicTree;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.FileEntity;
import com.lzxuni.modules.common.entity.PageData;
import com.lzxuni.modules.common.entity.PageParameter;
import com.lzxuni.modules.common.service.FileEntityService;
import com.lzxuni.modules.cropinformation.entity.TblCropInformation;
import com.lzxuni.modules.cropinformation.entity.TblPlantingInformation;
import com.lzxuni.modules.cropinformation.service.TblCropInformationService;
import com.lzxuni.modules.cropinformation.service.TblPlantingInformationService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 天气信息_苗青管理 前端控制器
 * </p>
 *
 * @author LaoNa
 * @since 2020-12-07
 */
@RestController
@RequestMapping("/Seed/Info")
public class SeedInfoController extends BaseController {

    @Autowired
    private SeedInfoService seedInfoService;


    @Autowired
    private TblCropInformationService tblCropInformationService;

    @Autowired
    private TblPlantingInformationService tblPlantingInformationService;
    @Autowired
    private FileEntityService fileEntityService;
    private String templatesPath="/Seed/Info";
    private String typeName = "苗情管理_信息";
    private String ywType = "seedPic";

    //主页面
    @RequestMapping("/Index")
    public ModelAndView Index() {
        ModelAndView mv = new ModelAndView(templatesPath+"/index");
        return mv;
    }

    //查询数据
    @RequestMapping("/GetList")
    public Object GetList(String pagination,String queryJson){
        PageParameter pageParameter = JSON.parseObject(pagination, PageParameter.class);
        SeedInfo seedInfo = JSON.parseObject(queryJson, SeedInfo.class);
        PageData pageData = getPageData(seedInfoService.queryPage(pageParameter, seedInfo));
        return R.ok().put("data", pageData);
    }


    //表单页
    @RequestMapping("/Form")
    public ModelAndView Form(String flag,String keyValue, String queryJson) throws Exception {
        ModelAndView mv = new ModelAndView(templatesPath + "/form");
        BasicTree basicTree = JSON.parseObject(queryJson, BasicTree.class);
        mv.addObject("basicTree", basicTree);
        FileEntity fileBeanCustom = new FileEntity();
        System.out.println(flag);
        if (basicTree != null && StringUtils.isNotBlank(basicTree.getTreeId())) {
            TblPlantingInformation tblPlantingInformation = tblPlantingInformationService.getOne(new QueryWrapper<TblPlantingInformation>().eq("land_id", basicTree.getTreeId()).eq("planting_year", DateFormatUtils.format(new Date(), "yyyy")));
            if (tblPlantingInformation != null && StringUtils.isNotBlank(tblPlantingInformation.getCropModela())) {
                TblCropInformation tblCropInformation=tblCropInformationService.getById(tblPlantingInformation.getCropModela());
                if (tblCropInformation != null ) {
                    mv.addObject("cropId",tblCropInformation.getCropId());
                    mv.addObject("cropName",tblCropInformation.getCropName());
                }
            }
        }
        if(StringUtils.isNotBlank(flag)&&!flag.equals("add")){
            fileBeanCustom.setYwId(keyValue);
            fileBeanCustom.setYwType(ywType);
            if(flag.equals("edit")){
                mv.addObject("seedPicNum", fileEntityService.queryNumByFileEntity(fileBeanCustom));
            }
            if(flag.equals("query")){
                List<FileEntity> fileEntities = fileEntityService.queryListByFileEntity(fileBeanCustom);
                mv.addObject("fileEntities",fileEntities);
            }
        }

        return mv;
    }

    //删除数据
    @RequestMapping("/DeleteForm")
    public Object delete(String keyValue) {
        seedInfoService.removeById(keyValue);
        return R.ok("删除成功");
    }

    //保存数据
    @RequestMapping("/SaveForm")
    public Object insertDo(String keyValue, SeedInfo seedInfo, String seedPic) throws Exception {

        seedInfo.setSeedId(keyValue);
        seedInfo.setCropId(seedInfo.getCropModel());
        if (StringUtils.isEmpty(seedInfo.getSeedId())) {
            String ywId = UuidUtil.get32UUID();
            seedInfo.setSeedId(ywId);
            if (!StringUtils.isEmpty(seedPic) && !"&amp;nbsp;".equals(seedPic)) {
                fileEntityService.insert(seedPic.replace("&quot;", "\""), ywId, typeName, ywType, null);
            }
            seedInfoService.save(seedInfo);
            return R.ok("保存成功");
        } else {
            fileEntityService.deleteByYwId(keyValue);
            if (!StringUtils.isEmpty(seedPic) && !"&amp;nbsp;".equals(seedPic)) {
                fileEntityService.insert(seedPic.replace("&quot;", "\""), keyValue, typeName, ywType, null);
            }
            seedInfoService.updateById(seedInfo);
            return R.ok("修改成功");
        }
    }
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, String queryJson, HttpServletRequest request) throws IOException {
        SeedInfo seedInfo = JSON.parseObject(queryJson, SeedInfo.class);

        BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
        String filename = "苗情管理" + DateUtil.DateToString(new Date(), "yyyyMMddHHmm") + ".xls";
        String agent = request.getHeader("User-Agent");
        filename = FileUtil.encodeDownloadFilename(filename, agent);
        String contentType = request.getSession().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        Workbook wb = null;
        try {
            wb = seedInfoService.exportExcel(seedInfo);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }



}

